<!-- 异常操作界面1 -->
<template>
	<view>
		<view v-if="exp !== '死种' && exp !== '死仔'">
			<view class="ul">
				<view v-for="(item,index) in list" :key="index" class="li" @tap="submit(item,exp)"
					@longpress="longPress(item)" @touchend="tounchend()" :style="Styles(item)">
					<span v-if="abnormalList[item-1] && abnormalList[item-1].refer"
						style="position: absolute;top:-55rpx;font-size: 20rpx;">记录中</span>
					<span>{{item}}</span>
				</view>
			</view>
		</view>
		<!-- 组件提示框 -->
		<u-toast ref="uToast" />
	</view>

</template>

<script>
	import {
		reqAbnormal,
		reqRecordOut,
		getExpection,
		reqExpection,
		deleteAbnormal
	} from '@/api/index.js'
	import {
		getNowDate
	} from '@/getTime.js'
	import {
		mapGetters
	} from 'vuex'
	import abnormal from '../../store/modules/abnormal';
	export default {
		components: {},
		props: {
			bgColor: {
				type: Array,
				required: true,
				validator: function(value) { //校验数组中每一项都为字符串
					return value.every(item => typeof item === 'string');
				}
			},
			chooseBgColor: {
				type: String,
				required: false
			},
			exp: {
				type: String,
				required: true
			},
			abnormal: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				list: [1, 4, 2, 5, 3, 6],
				abnormalList: [],
				formData: {
					siteId: uni.getStorageSync('siteId'),
					houseId: '',
					cageId: '',
					refer: ''
				},
				handle: '',
				show: false,
				content: '确认操作吗?',
				// 识别读取的是哪个按钮
				index: '',
				islongPress: false,
				connect: false,
				path: '',
			}
		},
		mounted() {
			this.requestAbnormal(); //请求异常状态
			// 监听全局事件
			this.$cage.$on('sednAbnormal', this.send);
			this.$cage.$on('abnormalsettle', this.Settle);
			this.$cage.$on('withdraw', this.withdraw);
		},
		beforeDestroy() {
			// 组件销毁前取消监听，防止内存泄漏
			this.$cage.$off('sednAbnormal', this.send);
			this.$cage.$off('abnormalsettle', this.Settle);
			this.$cage.$off('withdraw', this.withdraw);
		},
		async onLoad() {},
		computed: {
			...mapGetters(['nfcId']),
		},
		methods: {
			// 节流函数
			throttle(func, delay) {
				let lastCall = 0;
				let timeoutId;

				return function(...args) {
					const now = Date.now();

					if (now - lastCall >= delay) {
						// 立即执行
						func.apply(this, args);
						lastCall = now;
					} else {
						// 清除之前的延迟调用
						clearTimeout(timeoutId);

						// 延迟执行，确保在 delay 后可以执行
						timeoutId = setTimeout(() => {
							func.apply(this, args);
							lastCall = Date.now();
						}, delay - (now - lastCall));
					}
				};
			},
			//动态样式
			Styles(item) {
				if (this.abnormalList[item - 1] && this.abnormalList[item - 1].refer) {
					return {
						position: 'relative',
						background: this.bgColor[1]
					}
				} else {
					return {
						backgroundColor: this.bgColor[0]
					}
				}
			},
			// 判断是否为当前异常记录界面
			async send({
				abnormal,
				cageId
			}) {
				// 使用节流函数
				if (abnormal === this.abnormal) {
					// 创建节流的 sendAbnormal 函数
					const throttledSendAbnormal = this.throttle(async () => {
						await this.sendAbnormal(cageId, this.exp);
					}, 2000); // 2000毫秒的节流间隔
					// this.$refs.uToast.show({
					// 	title: `计数器${this.count}`,
					// 	type: 'warning',
					// 	duration: '800',
					// 	position: 'top'
					// });
					// 立即调用节流函数
					throttledSendAbnormal();
				}
			},
			async Settle({
				abnormal,
				cageId
			}) {
				// 使用节流函数
				if (abnormal === this.abnormal) {
					// 创建节流的 sendAbnormal 函数
					const throttledabnormalSettle = this.throttle(async () => {
						await this.abnormalSettle(cageId, this.exp);
					}, 2000); // 2000毫秒的节流间隔
					// 立即调用节流函数
					throttledabnormalSettle();
				}
			},
			async withdraw({
				abnormal,
				cageId
			}) {
				// 使用节流函数
				if (abnormal === this.abnormal) {
					// 创建节流的 sendAbnormal 函数
					const throttledabnormalwithdraw = this.throttle(async () => {
						await this.longPress(cageId, this.exp);
					}, 2000); // 2000毫秒的节流间隔
					// 立即调用节流函数
					throttledabnormalwithdraw();
				}
			},
			
			//请求异常记录
			async requestAbnormal() {
				try {
					const obj = {
						siteId: uni.getStorageSync('siteId'), //Cookie中的siteId
						houseId: this.nfcId, //store中的nfcId
						operation: this.abnormal //父组件传过来的props
					}
					const res = await getExpection(obj);
					this.abnormalList = res.abnormal
				} catch (error) {
					console.log('异常', error);
				}
			},
			//发送异常状态
			sendAbnormal(i, exp) {
				// 单击发请求
				// exp = this.exp;
				this.formData.cageId = i;
				this.formData.houseId = this.$store.state.NFC.nfcId; // 获取 houseId
				this.formData.refer = exp;
				this.$loading();

				if (exp === '淘汰') {
					reqRecordOut(this.formData).then(resp => {
						if (resp.msg === '已存在未处理的淘汰记录') {
							this.$refs.uToast.show({
								title: `${i}笼已是${exp}状态`,
								type: 'warning',
								duration: '800',
								position: 'top'
							});
						} else {
							const obj1 = {
								siteId: uni.getStorageSync('siteId'),
								houseId: this.nfcId
							};
							this.$store.dispatch('getStatu', obj1);
							const obj2 = {
								siteId: uni.getStorageSync('siteId'),
								houseId: this.nfcId,
								twoOrSix: 3
							};
							this.$store.dispatch('getDate', obj2);
							this.$refs.uToast.show({
								title: `已记录${i}笼${exp}异常`,
								type: 'success',
								duration: '800',
								position: 'top'
							});
							this.requestAbnormal(); // 重新请求异常更新界面
						}
					}).finally(() => {
						this.$hide();
					});
				} else {
					reqAbnormal(this.formData).then(data => {
						if (data.msg === '已存在') {
							this.$refs.uToast.show({
								title: `${i}笼已是${exp}状态`,
								type: 'warning',
								duration: '800',
								position: 'top'
							});
						} else {
							if (data.code === 200) {
								const obj1 = {
									siteId: uni.getStorageSync('siteId'),
									houseId: this.nfcId
								};
								this.$store.dispatch('getStatu', obj1);
								const obj2 = {
									siteId: uni.getStorageSync('siteId'),
									houseId: this.nfcId,
									twoOrSix: 3
								};
								this.$store.dispatch('getDate', obj2);
								this.$refs.uToast.show({
									title: `已记录${i}笼${exp}异常`,
									type: 'success',
									duration: '800',
									position: 'top'
								});
								this.requestAbnormal(); // 重新请求异常更新界面
							} else {
								this.$refs.uToast.show({
									title: data.msg,
									type: 'error',
									duration: '800',
									position: 'top'
								});
							}
						}
					}).catch(() => {
						this.$hide();
						this.$refs.uToast.show({
							title: data.msg,
							type: 'error',
							duration: '800',
							position: 'top'
						});
					}).finally(() => {
						this.$hide();
					});
				}
			},
			//发送解决异常请求
			async abnormalSettle(item, exp) {
				if (this.abnormalList[item - 1] && this.abnormalList[item - 1]
					.id) { // 判断异常是否存在记录 如果存在就可以解决
					const obj = {
						siteId: uni.getStorageSync('siteId'),
						cageId: item,
						houseId: this.nfcId,
						refer: exp,
						updateTime: getNowDate()
					};
					try {
						const response = await reqExpection(obj)
						console.log(response);
						if (response.code == 200) {
							// const result = await response.json(); 
							// console.log('撤回成功', response.msg);
							// 在这里处理成功响应，例如更新 UI
							this.requestAbnormal() //调用方法更新数组 更新ui
							this.$refs.uToast.show({
								title: `已解决${item}笼${this.exp}异常`,
								type: 'success',
								duration: '800',
								position: 'top',
							})
						} else {
							console.error('解决失败', response.statusText);
							// 在这里处理失败响应
							this.$refs.uToast.show({
								title: `解决${item}笼${this.exp}异常失败`,
								type: 'error',
								duration: '800',
								position: 'top',
							})
						}
					} catch (error) {
						console.error('请求错误', error);
						// 在这里处理请求错误
					}
				} else {
					this.$refs.uToast.show({
						title: `未记录，无法解决 cage为${item}`,
						type: 'error',
						duration: '800',
						position: 'top',
					})
				}
			},
			// 点击结束后将islongPress置为false，等待下一次操作 解决长按后出现自动单击现象
			tounchend() {
				setTimeout(() => {
					this.islongPress = false
				}, 200)
			},
			//长按撤回
			async longPress(item) {
				console.log('长按事件');
				this.islongPress = true;
				if (this.abnormalList[item - 1].id) { // 判断异常是否存在记录 如果存在就可以撤回
					const obj = {
						operation: this.abnormal,
						id: this.abnormalList[item - 1].id,
						siteId: uni.getStorageSync('siteId'),
						cageId: item,
						houseId: this.nfcId,
						time: this.abnormalList[item - 1].time
						// time: getNowDate()
					};
					try {
						const response = await deleteAbnormal(obj)
						console.log(response);
						if (response.code == 200) {
							// const result = await response.json(); 
							// console.log('撤回成功', response.msg);
							// 在这里处理成功响应，例如更新 UI
							this.requestAbnormal() //调用方法更新数组 更新ui
							this.$refs.uToast.show({
								title: `已撤回${item}笼${this.exp}异常`,
								type: 'warning',
								duration: '800',
								position: 'top',
							})
						} else {
							console.error('撤回失败', response.statusText);
							// 在这里处理失败响应
							this.$refs.uToast.show({
								title: `撤回${item}笼${this.exp}异常失败`,
								type: 'error',
								duration: '800',
								position: 'top',
							})
						}
					} catch (error) {
						console.error('请求错误', error);
						// 在这里处理请求错误
					}
				} else {
					this.$refs.uToast.show({
						title: `未记录，撤回${item}笼${this.exp}异常失败`,
						type: 'error',
						duration: '800',
						position: 'top',
					})
				}
			},
			// 单击或双击
			submit(item, exp) {
				this.cage_id = item.cage_id
				if (this.islongPress === false) {
					let _this = this
					let curTime = new Date().getTime()
					let lastTime = this
						.lastTime //this和_this 其实是不同时间的this 本质是一样的 this 和 _this 最终都指向同一个对象
					_this.lastTime = curTime
					let diff = curTime - lastTime; //时间间隔
					console.log('diff', diff)
					// 双击
					if (diff < 300) {
						setTimeout(() => {
							this.abnormalSettle(item, exp); //双击发送解决异常
							clearTimeout(_this.timer)
						})
					} else {
						_this.timer = setTimeout(() => {
							this.sendAbnormal(item, exp) //单击发送异常记录
						}, 300)
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.ul {
		display: flex;
		justify-content: space-around;
		align-content: space-around;
		width: 100%;
		height: 100%;
		flex-wrap: wrap;
		margin-top: 36.23rpx;

		.li {
			display: flex;
			flex-direction: column;
			margin: 32.91rpx 32.91rpx;
			text-align: center;
			align-items: center;
			width: 137.11rpx;
			height: 137.11rpx;
			line-height: 149.91rpx;
			font-size: 102.38rpx;
			font-weight: 700;
			list-style: none;
			border-radius: 36.23rpx;
			color: #fff;
			font-family: 'ExpectionNumber';

		}

		.exception_gray {
			position: relative;
			background: linear-gradient(135deg, #754359, #a92232 100%) !important;
			color: #fff;
		}

	}
</style>